﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Aliyun.OSS;

using Microsoft.Extensions.Options;

using Youshow.Ace.DependencyInjection;

namespace JackProjectTemplate.Storage.OSS
{
    public class OSSManager(IOptions<OSSOptions> ossOption) : IOSSManager
    {
        private readonly OssClient _ossClient = new(ossOption.Value.Endpoint, ossOption.Value.AccessKeyId, ossOption.Value.AccessKeySecret);

        public OssClient Client => _ossClient;

        public string BuildFullUrl(string filename) => $"{ossOption.Value.Host}/{filename}";

        public PutObjectResult PutObject(string filename, [NotNull] Stream stream, DateTime? expirationTime = default)
        {
            ObjectMetadata objectMetadata = new();
            objectMetadata.HttpMetadata["Last-Modified"] = DateTime.Now;
            objectMetadata.ContentLength = stream.Length;
            if (expirationTime.HasValue)
            {
                objectMetadata.ExpirationTime = expirationTime.Value;
            }

            return _ossClient.PutBigObject(ossOption.Value.BucketName, filename, stream, objectMetadata);
        }
    }

    public interface IOSSManager : ISingletonDependency
    {
        OssClient Client { get; }

        string BuildFullUrl(string filename);
        PutObjectResult PutObject(string filename, [NotNull] Stream stream, DateTime? expirationTime = null);
    }
}

// https://www.nuget.org/packages/Aliyun.OSS.SDK.NetCore
// https://www.aliyun.com/product/oss
// https://github.com/aliyun/aliyun-oss-csharp-sdk/blob/master/README-CN.md
